package controllers;

import java.util.TimerTask;

import controllers.SendMailSSL.SendMailRunnable;

import Entity.BorrowRecored;
import Entity.User;

import messagesPacks.BorrowAndUserMessage;

/**
 * This class starts a new timed thread that checks the orders table and sends
 * mail to subscribers that their order will be deleted because they didn't borrow
 * Their ordered books even though the book is viable to borrow.
 */

public class JobCheckOrders extends TimerTask 
{
	private DBController db_ref = null;
	private EchoServer echo_ref = null;
	private IntSysClock clk_ref = null;
	
	/**
	 * Sets up the timer thread.
	 * @author Alon Shahaf
	 * @Data 12.01.2013
	 * @param db	a reference to the DB controller
	 * @param echo  a reference to the communication class
	 * @param clk	a reference to the Clock class.
	 */
	public JobCheckOrders(DBController db, EchoServer echo, IntSysClock clk)
	{
		this.setDb_ref(db);
		this.setEcho_ref(echo);
		this.setClk_ref(clk);
	}
	
	public DBController getDb_ref() 
	{
		return db_ref;
	}

	public void setDb_ref(DBController db_ref) 
	{
		this.db_ref = db_ref;
	}
	
	public void setClk_ref(IntSysClock clk_ref) 
	{
		this.clk_ref = clk_ref;
	}
	
	public void setEcho_ref(EchoServer echo_ref) 
	{
		this.echo_ref = echo_ref;
	}
	
	/**
	 * Scans all the active orders and checks if the order is still valid.
	 * @author Alon Shahaf
	 * @Data 12.01.2013
	 */
    public void run() 
    {
    	int i=0;
    	System.out.println("(JOB - JobCheckOrders) "+clk_ref.getTime().toString()+ " Running..");
   		BorrowAndUserMessage data;
   		// Get all users that didn't come to take their order
   		data = db_ref.getAndDeleteOldOrders(clk_ref.getTime());
   		if ((data != null) && (data.hasGoodData()))
   		{
   			// Define N threads
   			Thread [] t = new Thread[data.getCounter()+1];
   			
   			// Prepare subject message
   			String subject = "OBL System - Your order has been deleted";
   			
   			// Send Email for each of those users
   			for (i=0; i<= data.getCounter(); i++)
   			{
				BorrowRecored br = data.getBorrow(i);
				User u = data.getUser(i);
				String isbn = br.bookISBN; 
				String id = br.userID;
				String start_date = br.borrowDate;
				String first_name = u.getFname();
				String last_name = u.getLname();
				String email = u.getEmail();
				String phone = u.getPhone();
				
				// Prepare body message
				String body = "Dear "+first_name+"," +
						"\n\n" +
						"Your order was active for 2 days and has been deleted.\n" +
						"Order details:\n"+
						"Order date - " + start_date + "\n" +
						"Book ISBN - " + isbn + "\n\n" +
						"Have a nice day,\n" +
						"OBL System.";
				
				// Create the thread
   				t[i] = new Thread(new SendMailRunnable(email,subject,body));

   				// Send Mail to the users that their order has been deleted
   				// Run the thread
   				t[i].start();
   			} // End of for
   			System.out.println("(JOB - JobCheckOrders) "+i+" Jobs activated.");

   			BorrowAndUserMessage data2;
   			// Define N threads
   			Thread [] t2 = new Thread[data.getCounter()+1];
   			
   			// Prepare subject message
   			subject = "OBL System - A book is waiting for you!";   			
   			
   			// Get the next users in the queue
   			for (i=0; i<= data.getCounter(); i++)
   			{
				BorrowRecored br = data.getBorrow(i);
				String search_next_isbn = br.bookISBN; 
				
				//System.out.println("(JOB - JobCheckOrders) ("+i+"/"+data.getCounter()+") Next order for ISBN="+search_next_isbn);
	   			data2 = db_ref.getNextOrderForBook(search_next_isbn);
	   			
	   			if ((data2 != null) && (data2.hasGoodData()))
	   			{
					BorrowRecored next_br = data2.getBorrow(0);
					User next_u = data2.getUser(0);
					String next_isbn = next_br.bookISBN;
					String next_start_date = next_br.borrowDate;
					String next_id = next_u.getID();
					String next_first_name = next_u.getFname();
					String next_last_name = next_u.getLname();
					String next_email = next_u.getEmail();
					String next_phone = next_u.getPhone();
					
					// Update actual return date to the orders table for this order. (needed for the scheduled job to know when to delete it)
					int updated_rows = db_ref.updateReturnDateInOrder(next_id,next_isbn);
					if (updated_rows > 0)
					{
						// Prepare body message
						String next_body = "Dear "+next_first_name+"," +
								"\n\n" +
								"Your requested book can be borrowed now\n" +
								"and will be saved for you for 2 days.\n"+
								"Order details:\n"+
								"Order date - " + next_start_date + "\n" +
								"Book ISBN - " + next_isbn + "\n\n" +
								"Have a nice day,\n" +
								"OBL System.";
						
						System.out.println("(JOB - JobCheckOrders) 1st for ISBN="+next_isbn+"  is ID= "+next_id);
						
		   				// Send them an email notifying it's their turn to borrow the book.
						t2[i] = new Thread(new SendMailRunnable(next_email,subject,next_body));
		   				// Run the thread
		   				t2[i].start();
					}
	   			}
   			}	// end of for (each book order)
   		}	// end of handling old orders from DB.
   		System.out.println("(JOB - JobCheckOrders) Finished iteration.");
   	} // end of run function
} // end of class
